#!/usr/bin/python
import sys, re, time
from optparse import OptionParser

stateMap = {"ok": "0", "warning": "1", "warn": "1", "crit":"2", "critical": "2", "unk": "3", "unknown": "3" }
reverseStateMap = {"0": "ok", "1": "warning", "2": "critical", "3": "unknown" }
status_dat_file = "/nems/nagios/var/status.dat"
#status_dat_file = "status.dat"
servicesArray = []
outputString = ""

class MyOptionParser(OptionParser):
    def error(self,msg):
        print msg
        sys.exit(3)
    #stolen from python library reference, add required option check
    def check_required(self, opt):
        option=self.get_option(opt)
        if getattr(self.values, option.dest) is None:
            self.error("%s option not supplied" % option)


try:
    parser = MyOptionParser(description="To read monitor status")
    parser.add_option("-H", "--host", dest="host", default=None, help="Hostname that needs to be searched. Ex: Device name showing in portal.")
    parser.add_option("-M", "--monitor", dest="monitor", default=None, help="Monitor that needs to be searched.")
    parser.add_option("-S", "--state", dest="state", default=None, help="State that needs to be searched. Ex: ok / warn / crit / unknown.")
    (options, args) = parser.parse_args()
except Exception, err:
    print >>sys.stderr, err.msg
    print >>sys.stderr, "for help use --help"
    sys.exit(3)

host = options.host
monitor = options.monitor
if options.state != None:
    state = stateMap.get(options.state.lower(), None) 
else:
    state = None

''' Reading NAGIOS status file to read the performance monitoring data '''
try:
    f = open(status_dat_file, "rb")
    raw_data = f.readlines()
    f.close()
except IOError:
    print >>sys.stderr, "Could not open the Monitoring state file %s." % (status_dat_file)
    sys.exit(1)

''' Preparing Google Protocol Buffered Data Format '''
try:
    arrayLength = len(raw_data)
    i = 0
    perf_pattern = re.compile("'[\w\s]+'=\-?[0-9\.]+|\S+=\-?[0-9\.]+")
    while i < arrayLength:
        if raw_data[i].strip().startswith('servicestatus {'):
            hash = {}
            ''' Loop through the whole block of "servicestatus" and prepare hash of values '''
            while raw_data[i].strip() != '}' and i < arrayLength:
                i += 1
                dataLine = raw_data[i].strip()
                if dataLine.startswith("host_name=") or dataLine.startswith("service_description=") or dataLine.startswith("check_interval=") or \
                dataLine.startswith("current_state=") or dataLine.startswith("last_hard_state=") or dataLine.startswith("plugin_output=") or \
                dataLine.startswith("performance_data=") or dataLine.startswith("last_check=") : 
                    valArr = dataLine.split("=", 1)
                    if len(valArr) > 1:
                        if valArr[0].strip() == "performance_data":
                            valArr[1] = re.sub("\s+=\s+", "=", valArr[1].strip())
                        hash[valArr[0].strip()] = valArr[1].strip()
                    else:
                        hash[valArr[0].strip()] = ""
            
            if (host == None or hash["host_name"] == host) and (state == None or hash["current_state"] == state ) and (monitor == None or hash["service_description"] == monitor):
                servicesArray.append(hash)
        i += 1

except Exception, emsg:
    print ('Error - ' + str(emsg))
    sys.exit(1)

epoch = int(time.time())
outputString += "\"Hostname\", \"Monitor\", \"Current State\", \"Last Updated Time\", \"Output\", \"Performance Data\"\n"

for item in servicesArray:
    outputString += "\"%s\",  \"%s\",  \"%s\",  \"%s Minutes\",  \"%s\", \"%s\"\n" % (item['host_name'], item['service_description'], reverseStateMap.get(item['current_state'], 'Monitor State-'+item['current_state']), (int(epoch)-int(item['last_check'])) / 60, item['plugin_output'], item['performance_data'])

print outputString
